<?php
declare (strict_types=1);

namespace app\shop\controller;

use app\shop\middleware\Check;
use app\shop\model\Category;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\facade\Validate;
use think\facade\View;
use think\Request;

class Goods
{

    // 在控制器使用中间件
    protected $middleware = [Check::class];

    /**
     * 商品列表
     */
    public function list(Request $request)
    {

        $goods_name = $request->get('goods_name');//接收get请求的参数
        $cate_one_id = $request->get('cate_one_id');
        $cate_two_id = $request->get('cate_two_id');
        $cate_three_id = $request->get('cate_three_id');

        $where = [];
        # 添加搜索条件之前需要做处理 组装搜索条件
        # 查询一级分类数据
        $category_one = Category::where('pid', '=', 0)->select();
        $category_two = [];
        $category_three = [];
        if ($cate_three_id > 0) {
            $where[] = ['cate_id', '=', $cate_three_id];
            $category_two = Category::where('pid', '=', $cate_one_id)->select();// 二级分类数据
            $category_three = Category::where('pid', '=', $cate_two_id)->select();// 三级分类数据
        }

        if (!empty($goods_name)) {
            $where[] = ['goods_name', 'like', "%$goods_name%"];
        }

        # 分页查询数据

        # 添加查询条件、方法一
        # 添加搜索条件
        $data = \app\shop\model\Goods::where($where)->order('id', 'desc')->paginate([
            'list_rows' => 5,
            'query' => [
                'cate_one_id' => $cate_one_id,
                'cate_two_id' => $cate_two_id,
                'cate_three_id' => $cate_three_id,
                'goods_name' => $goods_name,
            ]
        ]);// 保留搜索条件使用query url额外的参数 页码后面的追加的参数


        View::assign([
            'data' => $data,// 数据集合
            'category_one' => $category_one,// 一级分类
            'category_two' => $category_two,// 二级分类
            'category_three' => $category_three,// 三级分类
            'goods_name' => $goods_name, //搜索条件名称
            'cate_one_id' => $cate_one_id,// 一级分类id
            'cate_two_id' => $cate_two_id,// 二级分类id
            'cate_three_id' => $cate_three_id,// 三级分类id
        ]);// 发送到视图、为了表单的展示

        return View::fetch('/goods_list');
    }

    /**
     * 获取父级下面的子分类
     */
    public function getChildCategory()
    {
        $id = \request()->get('id');
        # 查询子分类
        $category = Category::where('pid', '=', $id)->select()->toArray();
        return json(['data' => $category, 'code' => 200, 'msg' => '查询成功']);
    }

    /**
     * 批量删除
     */
    public function batchDel(Request $request)
    {
        $ids = $request->post('ids');

        $result = \app\shop\model\Goods::destroy($ids);
        if ($result) {
            return json(['data' => [], 'code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['data' => [], 'code' => 2001, 'msg' => '删除失败']);
        }
    }

    /**
     * 展示添加页面
     */
    public function add()
    {
        // 指定视图文件 默认访问的是控制名对应目录下面的方法名对应文件名
        return View::fetch('/goods_add');
    }

    /**
     * 实现数据添加
     */
    public function goodsSave(Request $request)
    {

        try {
            # 接收所有的参数、包含文件上传的信息
            $param = $request->all();

            # 方法一
            # 调用验证 创建验证类 php think make:validate 应用名称@验证名称
            validate(\app\shop\validate\Goods::class)->check($param);

            # 方法二 不用创建验证类
//            $validate = Validate::rule(['goods_name' => 'require','goods_number' => 'require|number'])->message([
//                'goods_name.require' => '商品名称必填'
//            ]);
//            $result = $validate->check($param);
//            if (!$result) {
//                # 验证不通过 、获取验证信息
//                dd($validate->getError());
//            }


            # 接收单独文件上传信息
//        $file = $request->file('goods_logo');
            # 默认存储到runtime目录
//        $path = Filesystem::putFile('goods_logo',$param['goods_logo']);
            # 可以修改存储位置
            $path = Filesystem::disk('public')->putFile('goods_logo', $param['goods_logo']);
            # 入库 方法一
            $goodsModel = new \app\shop\model\Goods();
            $data = [
                'goods_name' => $param['goods_name'],
                'goods_price' => $param['goods_price'],
                'goods_number' => $param['goods_number'],
                'goods_logo' => '/storage/' . $path,
                'goods_introduce' => $param['goods_desc'],
            ];
            $result = $goodsModel->save($data);

//        方法二
//        $result = \app\shop\model\Goods::create($data);
            if ($result) {
                return redirect('/shop/goodsList');
            }
            return redirect('/shop/goodsAdd');

        } catch (ValidateException $validateException) {
            dd($validateException->getError());// 输出错误信息
        }

    }


    /**
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\think\response\Redirect
     */
    public function delete($id)
    {
        if (!is_numeric($id)) {
            dd("参数不正确");
        }
        $result = \app\shop\model\Goods::destroy($id);
        if ($result) {
            return redirect('/shop/goodsList');
        }
        dd("删除失败");
    }


    /**
     * 编辑数据
     */
    public function edit($id)
    {
        $info = \app\shop\model\Goods::find($id);

        View::assign('info', $info);

        return View::fetch('/goods_edit');
    }

    /**
     * 更新入库
     */
    public function update(Request $request)
    {
        $param = $request->all();

        # 参数验证

//        修改时 也想使用Goods验证类
        // 修改的时候有id、logo可传、可不传

        try {
            # 使用编辑的验证
            \validate(\app\shop\validate\Goods::class)->scene('Editor')->check($param);

        } catch (ValidateException $validateException) {
            dd($validateException->getError());
        }
        // 但是修改和添加的验证信息有异样


        # 更新入库的数据
        $data = [
            'goods_name' => $param['goods_name'],
            'goods_price' => $param['goods_price'],
            'goods_number' => $param['goods_number'],
            'goods_introduce' => $param['goods_introduce'],
        ];

        # 可以使用has方法来检测一个变量参数是否设置
        if (isset($param['goods_logo'])) {
            # 修改图片
            $path = Filesystem::disk('public')->putFile('goods_logo', $param['goods_logo']);
            $data['goods_logo'] = '/storage/' . $path;
            unlink($param['old_goods_logo']);
        }

        \app\shop\model\Goods::update($data, ['id' => $param['id']]);
        return redirect('/shop/goodsList');

    }

    /**
     * 状态的修改
     */
    public function updateStatus(Request $request)
    {
        $id = $request->post('id');
        if (!is_numeric($id)) {
            return json(['data' => [], 'msg' => 'id参数错误', 'code' => 2001]);
        }

        # 状态修改
        $info = \app\shop\model\Goods::find($id);
        $info->goods_status = $info->goods_status == 2 ? 1 : 2;
        $info->save();
        return json(['data' => [], 'msg' => 'ok', 'code' => 200]);
    }


    /**
     * 文件上传的接口
     */

    public function uploadImage()
    {
        // request()    助手函数 view()
        # 二维数组 循环处理
        $files = \request()->all();
        $path = [];
        foreach ($files as $item) {
            $path[] = [
                'url' => 'http://www.2005afirst.com/storage/' . Filesystem::disk('public')->putFile('wang', $item),
                'alt' => '文字说明',
                'href' => '#',
            ];
        }

        $data = [
            'errno' => 0,
            'data' => $path
        ];
        return json($data);
    }


    /**
     * 在控制器里面调用公共函数
     */
    public function common()
    {

        # 真实的密码 123456
        # 黑客破解后的字符串
//        MIICXAIBAAKBgQC8kGa1pSjbSYZVebtTRBLxBz5H4i2p/llLCrEeQhta5kaQu/Rn
//vuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t0tyazyZ8JXw+KgXTxldMPEL9
//5+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4ehde/zUxo6UvS7UrBQIDAQAB
//AoGAb/MXV46XxCFRxNuB8LyAtmLDgi/xRnTAlMHjSACddwkyKem8//8eZtw9fzxz
//bWZ/1/doQOuHBGYZU8aDzzj59FZ78dyzNFoF91hbvZKkg+6wGyd/LrGVEB+Xre0J
//Nil0GReM2AHDNZUYRv+HYJPIOrB0CRczLQsgFJ8K6aAD6F0CQQDzbpjYdx10qgK1
//cP59UHiHjPZYC0loEsk7s+hUmT3QHerAQJMZWC11Qrn2N+ybwwNblDKv+s5qgMQ5
//5tNoQ9IfAkEAxkyffU6ythpg/H0Ixe1I2rd0GbF05biIzO/i77Det3n4YsJVlDck
//ZkcvY3SK2iRIL4c9yY6hlIhs+K9wXTtGWwJBAO9Dskl48mO7woPR9uD22jDpNSwe
//k90OMepTjzSvlhjbfuPN1IdhqvSJTDychRwn1kIJ7LQZgQ8fVz9OCFZ/6qMCQGOb
//qaGwHmUK6xzpUbbacnYrIM6nLSkXgOAwv7XXCojvY614ILTK3iXiLBOxPu5Eu13k
//eUz9sHyD6vkgZzjtxXECQAkp4Xerf5TGfQXGXhxIX52yH+N2LtujCdkQZjXAsGdm
//B2zNzvrlgRmgBrklMTrMYgm1NPcW+bRLGcwgW2PTvNM=123456
//        $rand = 'MIICXAIBAAKBgQC8kGa1pSjbSYZVebtTRBLxBz5H4i2p/llLCrEeQhta5kaQu/Rn
//vuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t0tyazyZ8JXw+KgXTxldMPEL9
//5+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4ehde/zUxo6UvS7UrBQIDAQAB
//AoGAb/MXV46XxCFRxNuB8LyAtmLDgi/xRnTAlMHjSACddwkyKem8//8eZtw9fzxz
//bWZ/1/doQOuHBGYZU8aDzzj59FZ78dyzNFoF91hbvZKkg+6wGyd/LrGVEB+Xre0J
//Nil0GReM2AHDNZUYRv+HYJPIOrB0CRczLQsgFJ8K6aAD6F0CQQDzbpjYdx10qgK1
//cP59UHiHjPZYC0loEsk7s+hUmT3QHerAQJMZWC11Qrn2N+ybwwNblDKv+s5qgMQ5
//5tNoQ9IfAkEAxkyffU6ythpg/H0Ixe1I2rd0GbF05biIzO/i77Det3n4YsJVlDck
//ZkcvY3SK2iRIL4c9yY6hlIhs+K9wXTtGWwJBAO9Dskl48mO7woPR9uD22jDpNSwe
//k90OMepTjzSvlhjbfuPN1IdhqvSJTDychRwn1kIJ7LQZgQ8fVz9OCFZ/6qMCQGOb
//qaGwHmUK6xzpUbbacnYrIM6nLSkXgOAwv7XXCojvY614ILTK3iXiLBOxPu5Eu13k
//eUz9sHyD6vkgZzjtxXECQAkp4Xerf5TGfQXGXhxIX52yH+N2LtujCdkQZjXAsGdm
//B2zNzvrlgRmgBrklMTrMYgm1NPcW+bRLGcwgW2PTvNM=123456';
//        echo md5($rand+'123456');
//        echo md5('12b3a4a5a6');die();

//        echo sum(2,10);die();
        echo avg([2, 8, 5, 6, 8, 8, 7, 7, 3]);// 调用公共函数 使用函数名字即可调用
    }
}
